/**
 * 获取用户个人资料接口
 */

//引入Q模块
let Q = require('q');

//存放redis模块
let redis;

//getProfile入口函数
let index = function(getData, postData, config, _redis, db) {
	redis = _redis;
	let deferred = Q.defer();
	let userId;
	getUserId(postData._3rdSession).then(function(_userId) {
		userId = _userId;
		return db.connectDB('common');
	}, function() {
		//获取用户ID失败
		deferred.reject('-0081');
	}).then(function(commonDB) {
		return commonDB.select('users', {
			userId: userId
		});
	}, function() {
		//连接到公共数据库失败
		deferred.reject('-0127');
	}).then(function(userProfile) {
		if(userProfile[0]) {
			deferred.resolve(userProfile[0]);
		}
		else {
			//不存在这个用户
			deferred.reject('-0195');
		}
	}, function() {
		//获取用户数据失败
		deferred.reject('-0196');
	});
	return deferred.promise;	
}

let getUserId = function(_3rdSession) {
	let deferred = Q.defer();
	redis.get(_3rdSession).then(function(data) {
		if(data) {
			data = JSON.parse(data);
			if(data.openId) {
				deferred.resolve(data.openId);
			}
			else {
				deferred.reject();
			}
		}
		else {
			deferred.reject();
		}
	}, function(err) {
		console.log(err);
		deferred.reject();
	});
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
};